import axios from 'axios'
import qs from 'qs'
//设置post请求头
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.withCredentials=false;//跨域请求

//创建axios实例
const instance =axios.create({
    timeout:300000,
});
//请求拦截
instance.interceptors.request.use((config)=>{
    console.log("请求拦截",config);
    return config;
},(error)=>{
    return Promise.reject(error)
})
//响应拦截
instance.interceptors.response.use((response)=>{
    console.log("响应拦截",response);
    if (response.status && response.status == 200 && response.data.status == 500) {
        Message.error({message: response.data.msg})
        return;
    }
    if (response.data.msg) {
        Message.success({message: response.data.msg})
    }
    return response;
},(error)=>{
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message: '服务器被吃了( ╯□╰ )'})
    } else if (error.response.status == 403) {
        Message.error({message: '权限不足，请联系管理员'})
    } else if (error.response.status == 401) {
        mymessage.error({message: error.response.data.msg ? error.response.data.msg : '尚未登录，请登录'})
        router.replace('/');
    } else {
        if (error.response.data.msg) {
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误!'})
        }
    }
    console.log('catch', error)
    return Promise.reject(error)
})

//按照请求类型对axios进行封装
const api={
    get(url,data){
        return instance.get(url,{params:data})
    },
    post(url,data){
        return instance.post(url,qs.stringify(data))
    }
}
//暴露
export {api}